import os
from flask import Blueprint, jsonify, request,json
import urllib
from config import Config
from handle.logger import logger
from handle.auth import *
import hashlib
auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['POST'])
def login():
    #记录请求IP和URL
    
    logger.info(request.remote_addr+"\n"+request.url+"\n"+request.data.decode('utf-8'))
    data=request.json
    if "username" in data and "password" in data:
        
        rs=get_user_cache(data["username"])
        
        if  rs != None:
            return json.dumps({"status": 200,"message": "Login success","request_data": request.json},sort_keys=False)
        else:
            return json.dumps({"status": 201,"message": "Login failed","request_data": request.json},sort_keys=False)
    else:
        return json.dumps({"status": 400,"message": "username or password is null"},sort_keys=False)

@auth_bp.route('/logout', methods=['GET','POST'])
def logout():
    
    logger.info(request.remote_addr+request.url)
    if del_session():
        return json.dumps({"status": 200,"message": "Logout success"},sort_keys=False)
    else:
        return json.dumps({"status": 201,"message": "Logout failed"},sort_keys=False)

@auth_bp.route('/third-party', methods=['POST'])
def third_party_auth():
    
    logger.info(request.remote_addr+request.url)
    if check_session():
        return json.dumps({"status": 200,"message": "Third-party auth success"},sort_keys=False)
    else:
        return json.dumps({"status": 201,"message": "Third-party auth failed"},sort_keys=False)

@auth_bp.route('/third-party', methods=['GET'])
def third_party_list():
    folder_path = "upload/img/sq/"
    images = []
    for file_name in os.listdir(folder_path):
        if file_name.endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):  # 检查是否是图片文件
            # 去掉文件扩展名作为名称
            name = os.path.splitext(file_name)[0]
            # 添加图片信息到列表
            images.append({
                "name": name.replace('_', ' '),  # 用空格替换下划线
                "img": Config.URL + folder_path + file_name
            })
    return json.dumps({"status": 200,"message": "Third-party list","data": images},sort_keys=False)
